#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>

#include "thread_upgrade.h"
#include "thread_comm.h"

#define UPGRADE_DBG     1
#define UPGRADE_ERR     1
#define UPGRADE_MODULE_TAG  " [UPGRADE]"

#if UPGRADE_DBG
#define UPGRADE_DBG_MSG(format, arg...) \
    do  \
    {   \
        printf("%s""<%d>===> "format, UPGRADE_MODULE_TAG,__LINE__,##arg);  \
    }   \
    while (0);
#else
#define UPGRADE_DBG_MSG(format, arg...)
#endif


#if UPGRADE_ERR
#define UPGRADE_ERR_MSG(format, arg...) \
    do  \
    {   \
        printf("%s""<%d>===> "format, UPGRADE_MODULE_TAG,__LINE__,##arg);  \
    }   \
    while (0);
#else
#define UPGRADE_ERR_MSG(format, arg...)
#endif


EN_ERROR_CODE thread_upgrade_get_msg(ST_MSG msg)
{	
    EN_ERROR_CODE err = EN_ERROR_CODE_FAIL;

    if ( MSG_T_UPGRADE != msg.type ) 
    {
        return EN_ERROR_CODE_MSG_TYPE_FAIL;
    }
    if(NULL!=msg.p2)
    {
        free(msg.p2);
    }

    //start upgrade module
    FILE *ufp = NULL;
    ufp = fopen(UPGRADE_PATH, "r");
    if(ufp==NULL)
    {
        perror("fopen upgrade file\n");
        return -1;
    }

    fclose(ufp);
    

    err =system("cd /dev/upgrade/;tar -zxf upgrade.tar.gz");
    UPGRADE_DBG_MSG("err:%d\n",err);
    err =system("rm  /dev/upgrade/upgrade.tar.gz");
    UPGRADE_DBG_MSG("err:%d\n",err);
    err =system("cp -rf  /dev/upgrade/*  /mnt/mtd/");
    sleep(1);
    UPGRADE_DBG_MSG("err:%d\n",err);
    UPGRADE_DBG_MSG("upgrade finish!reboot......\n");
    err = EN_ERROR_CODE_SUCCESS;
    //create upgrade flg file
    if(EN_ERROR_CODE_SUCCESS == err)
    {
        FILE *fp = NULL;
        fp = fopen(UPGRADE_FLG_PATH, "w");
        if ( fp == NULL )
        {
            perror("fopen\n");
            return -1;
        }
        fclose(fp);
        system("reboot");
    }
    
	return err;
}

void *thread_upgrade(void *arg)
{
    int ret;
    ST_MSG msg;
    
    while (1)
    {
        ret = msgrcv(*((int*)arg), (void*)&msg, MSG_CONT_LEN, MSG_T_UPGRADE, 0);
        if ( ret < 0 )
        {
            perror("msgrcv");
        }
        UPGRADE_DBG_MSG("RECV MSG %d\n", msg.type);
		thread_upgrade_get_msg(msg);
    }
    return ( ( void * )EN_ERROR_CODE_SUCCESS ); 

}



